var currentRecord = new Ext.data.Record();

var roleStore = new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({
				url : 'authorize.action?method=getAllRole',
				method:'GET'
			}),
			reader : new Ext.data.JsonReader({
				id : 'id',
				root : 'data',
				totalProperty : 'totalProperty',
				fields : [
					{name : 'id',mapping : 'id'},
					{name : 'name', mapping : 'name'},
					{name : 'status', mapping : 'status'},
					{name : 'remark', mapping : 'remark'}
				]
			})
		});
		
var roleGrid = new Ext.grid.GridPanel({
    	height:Ext.get("content").getHeight(),
    	viewConfig:{forceFit:true},//自动填充列宽.
    	store : roleStore,
    	cm : new Ext.grid.ColumnModel([
			new Ext.grid.CheckboxSelectionModel(),
			new Ext.grid.RowNumberer({header:'行号',width:40}),
	        {header: '角色名称', dataIndex: 'name', width: 100, sortable : true},
	        {header: '状态', dataIndex: 'status', width: 100},   
	        {header: '备注', dataIndex: 'remark', width: 100}
	    ]),
    	trackMouseOver : false,
    	sm : new Ext.grid.CheckboxSelectionModel(),
    	tbar : new Ext.Toolbar([
	    	{text:'添加角色',icon:'icons/toolBar/add.gif',handler:addRole},
	    	{text:'修改角色',icon:'icons/toolBar/plugin.gif',handler:modifyRole},
	    	{text:'删除角色',icon:'icons/toolBar/delete.gif',handler:delRole},
	    	{text:'授权',icon:'icons/toolBar/add.gif',handler:showAuthority}
	    ])
    });

    roleGrid.getSelectionModel().on('rowselect',function(sm, rowIdx, r){
    	currentRecord = r;
    });
    
function addRole(){
	roleForm.getForm().reset();
	roleForm.isAdd = true;
	roleFormWin.setTitle('添加角色');
	roleFormWin.show();
}

function modifyRole(){
	if(currentRecord == null){
		Ext.Msg.alert('提示','请选择需要修改的角色!');
	}else{
		roleForm.getForm().reset();
		roleForm.isAdd = false;
		loadRoleData();
	}
}

function delRole(){
	var records = []; 
	records = roleGrid.getSelectionModel().getSelections();
	if(records.length < 1){
		Ext.Msg.alert('提示','请选择要删除的角色!')
	}else{
		var roleIds = [];
		for(var i=0; i < records.length; i++){
			roleIds[i] = records[i].get('id');
		}
		
		var roleDeleteTip = Ext.MessageBox.show({
			msg: '正在删除所选项目, 稍后...',
	        progressText: '删除...',
	        width:300,
	        wait:true,
	        waitConfig: {interval:200}
		});
		
		Ext.Ajax.request({
			url : 'authorize.action?method=deleteRole',
			params : {'roleIds' : roleIds},
			method : 'POST',
			success : function(response, options) {
				roleDeleteTip.hide();
				var result = Ext.util.JSON.decode(response.responseText);
				if (result.success) {
					for (var i = 0; i < roleIds.length; i++) {
						var index = roleStore.find('id', roleIds[i]);
						if (index != -1) {
							var rec = roleStore.getAt(index);
							roleStore.remove(rec);
						}
					}
					Ext.Msg.alert('提示', '成功删除项目');
				}
			},
			failure : function(response, options) {
				roleDeleteTip.hide();
				Ext.Msg.alert('提示', '该角色可能已经授予某个用户，系统不允许删除!.');
			}
		});
	}
}


function getSelectedRole(){
	var records = [];
	var ids = [];
	records = roleGrid.getSelectionModel().getSelections();
	for(var i=0; i<records.length; i++){
		ids.push(records[i].get('id'));
	}
	return ids;
}

//========== Form =============
Ext.form.Field.prototype.msgTarget = 'side';
var roleForm = new Ext.FormPanel({
	labelSeparator : ':',
	frame : true,
	border:false,
	items:[{
			xtype:'textfield',
			width:200,
			allowBlank:false,
			blankText : '角色名不能为空!',
			name:'name',
			fieldLabel : '角色名称'
		},{
			xtype:'textfield',
			width:200,
			name:'status',
			fieldLabel : '角色状态'
		},{
			xtype:'textfield',
			width:200,
			name:'remark',
			fieldLabel : '说明'
		},{
			xtype:'hidden',
			name : 'id'
		}
	],
	buttons:[
		{
			text : '关闭',
			handler : function(){
				roleFormWin.hide();
			}
		},{
			text : '提交',
			handler : submitRoleForm
		}
	]
});

var roleFormWin = new Ext.Window({
		layout:'fit',
		width:380,
		height:400,
		closeAction:'hide',
		resizable:false,//true可以拖动大小.
		shadow : true,//投影效果.
		modal:true,//对后面内容进行遮盖.
		closable:true,
		bodyStyle:'padding:5 5 5 5',
		animCollapse:true,//关闭面板是的动画效果.
		items:[roleForm]
});

function submitRoleForm(){
	var postUrl;
	if(roleForm.isAdd){
		postUrl = 'authorize.action?method=addRole'
	}else{
		postUrl = 'authorize.action?method=modifyRole'
	}
	roleForm.getForm().submit({
			clientValidation:true,
    		waitMsg:'正在执行操作',
    		waitTitle:'提示',
    		url:postUrl,
    		method:'POST',
    		success:function(form,action){
    			roleFormWin.hide();
    			roleStore.reload();
    			Ext.Msg.alert('提示','操作成功');
    		},
    		failure:function(form,action){
    			Ext.Msg.alert('提示','操作失败');
    		}
		});
}

function loadRoleData(){
	roleForm.getForm().load({
		waitMsg : '正在加载数据',
		waitTitle : '提示',
		url : 'authorize.action?method=loadRole',
		params : {'roleId':currentRecord.get('id')},
		method : 'GET',
		success : function(form,action){
			roleFormWin.setTitle('修改角色');
			roleFormWin.show();
		},
		failure : function(form,action){
			Ext.Msg.alert('无法加载该数据');
		}
	});
}

//======= END ==========
Ext.onReady(function(){
	currentRecord = null;
	roleGrid.render('rolePanel');
	roleStore.load();
});